package com.hhs.storage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhs.storage.bean.*;
import com.hhs.storage.bean.dto.WeightStats;
import com.hhs.storage.dao.BusinessDocumentDao;
import com.hhs.storage.service.BaseRoleService;
import com.hhs.storage.service.BusinessDocumentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhs.storage.service.ComsumerService;
import com.hhs.storage.service.ContractService;
import com.hhs.storage.util.SysUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hhs
 * @since 2023-01-04
 */
@Service
@Lazy
@Transactional
public class BusinessDocumentServiceImpl extends ServiceImpl<BusinessDocumentDao, BusinessDocument> implements BusinessDocumentService {
    @Autowired
    private ContractService contractService;
    @Autowired
    private ComsumerService comsumerService;
    @Autowired
    private BaseRoleService roleService;
    @Autowired
    BusinessStatsService businessStatsService;
    @Resource
    private HttpServletRequest request;
    @Override
    public Map<String, Object> getAll(BusinessDocument businessDocument, InputParam inputParam,boolean isSelf) {
        QueryWrapper ew = new QueryWrapper<BusinessDocument>();
        if (isSelf){//是否只查询与自身相关数据
            ew.eq("creator", SysUtil.getLoginUserId(request));//查询自身相关单据
        }

        if(!StringUtils.isEmpty(inputParam.getName())){
            //根据合同名称查询
            ew.inSql("contract_id","select id from contract where project like '%"+inputParam.getName()+"%'");
        }
        if(!StringUtils.isEmpty(inputParam.getContractType())){
            //根据合同类型查询
            ew.inSql("contract_id","select id from contract where contract_type = '"+inputParam.getContractType()+"'");
        }
        if(businessDocument.getState()!=null){
            //根据状态查询
            ew.eq("state",businessDocument.getState());
        }
        ew.orderByDesc("create_time");
        Page<BusinessDocument> result = this.page(new Page<BusinessDocument>(
                inputParam.getPage(),
                inputParam.getSize()),ew);
        Map<String, Object> map = new HashMap<String, Object>();
        List<BusinessDocument> rows=result.getRecords();
        for (int i = 0; i < rows.size(); i++) {
            BusinessDocument temp=rows.get(i);
            Contract contract=contractService.getById(temp.getContractId());
            temp.setContract(contract);
            Comsumer comsumer=comsumerService.getById(temp.getCustomerId());
            temp.setComsumer(comsumer);
        }
        map.put("rows", rows);
        map.put("total",result.getTotal());
        map.put("code", 1);
        return map;
    }

    @Override
    public Map<String, Object> addOrUpdate(BusinessDocument businessDocument) {
        if(StringUtils.isEmpty(businessDocument.getContractId()) ||
                StringUtils.isEmpty(businessDocument.getNum())||
//                StringUtils.isEmpty(businessDocument.getModelType())||
                StringUtils.isEmpty(businessDocument.getCustomerId())||
                StringUtils.isEmpty(businessDocument.getUnit())){
            return ResponseInfo.error("参数错误");
        }
        //新增
        if (StringUtils.isEmpty(businessDocument.getId())) {
            //检查当前角色是否业务员
//           boolean flag= roleService.hasRole(SysUtil.ROLE_FLAG_YWY,SysUtil.getLoginUserId(request));
//           if (!flag){
//               return ResponseInfo.error("只有业务员才可以下单");
//           }
            businessDocument.setCreateTime(LocalDateTime.now());
            businessDocument.setId(SysUtil.UUID());
            businessDocument.setCreator(SysUtil.getLoginUserId(request));
            businessDocument.setState(BusinessDocument.STATUS_CREATE);//设置默认待下单
            this.save(businessDocument);
        } else {//修改
//            this.updateById(businessDocument);
        }
        return ResponseInfo.success(null);
    }

    @Override
    public Map dele(String id) {
        if(StringUtils.isEmpty(id)){
            return ResponseInfo.error("参数错误");
        }
        this.removeById(id);
        return ResponseInfo.success(null);
    }

    @Override
    public Map<String, Object> getAllHis(BusinessDocument businessDocument, InputParam inputParam) {

        QueryWrapper ew = new QueryWrapper<BusinessDocument>();
        String userId = SysUtil.getLoginUserId(request);
        boolean isYWY=roleService.hasOnlyRole(SysUtil.ROLE_FLAG_YWY,userId);
        if (isYWY){ //如果是业务员，则只查询自己
            ew.eq("creator", userId);//查询自身相关单据
        }

        if(!StringUtils.isEmpty(inputParam.getName())){
            //根据合同名称查询
            ew.inSql("contract_id","select id from contract where project like '%"+inputParam.getName()+"%'");
        }
        if(!StringUtils.isEmpty(inputParam.getContractType())){
            //根据合同类型查询
            ew.inSql("contract_id","select id from contract where contract_type = '"+inputParam.getContractType()+"'");
        }
        if(!StringUtils.isEmpty(inputParam.getDateStr())){
            //某日的数据
            String startTime = inputParam.getDateStr()+" 00:00:00";
            String endTime = inputParam.getDateStr()+" 23:59:59";
            ew.ge("create_time",startTime);
            ew.le("create_time",endTime);
        }
        ew.eq("state",1);
        ew.orderByDesc("create_time");
        Page<BusinessDocument> result = this.page(new Page<BusinessDocument>(
                inputParam.getPage(),
                inputParam.getSize()),ew);
        Map<String, Object> map = new HashMap<String, Object>();
        List<BusinessDocument> rows=result.getRecords();
        for (int i = 0; i < rows.size(); i++) {
            BusinessDocument temp=rows.get(i);
            Contract contract=contractService.getById(temp.getContractId());
            temp.setContract(contract);
            Comsumer comsumer=comsumerService.getById(temp.getCustomerId());
            temp.setComsumer(comsumer);
            //查询出该单据已运送的卸货吨数
            StatsParam statsParam = new StatsParam();
            statsParam.setDocuId(temp.getId());
            WeightStats weightStats = businessStatsService.weightStatsForTable(statsParam);
            if(weightStats!=null && weightStats.getWeightUnload()!=null && weightStats.getWeightUnload().compareTo(new BigDecimal(0))>0){
                String tip="已卸货："+weightStats.getWeightUnload()+"吨";
                if(StringUtils.isEmpty(temp.getRemark())){
                    temp.setRemark(tip);
                }else{
                    temp.setRemark(temp.getRemark()+tip);
                }
            }
        }
        map.put("rows", rows);
        map.put("total",result.getTotal());
        map.put("code", 1);
        return map;
    }
}
